#include "TimeRecordUtil.h"

int TimeRecordUtil::_TimeRecordIDAlloactor = 0;

int TimeRecordUtil::NewRecord()
{
	return _TimeRecordIDAlloactor++;
}

clock_t TimeRecordUtil::MakeRecord(int handler)
{
	_RecordTimePoints[handler].push_back(clock());
	return _RecordTimePoints[handler].back();
}

clock_t TimeRecordUtil::Collapse(int handler)
{
	if(_RecordTimePoints[handler].size() < 2)
		return 0;
	auto& records = _RecordTimePoints[handler];
	clock_t interval = records[records.size() - 1] - records[records.size() - 2];
	records.pop_back();
	records.pop_back();

	_RecordTimeIntervals[handler].push_back(interval);
	return interval;
}

void TimeRecordUtil::CloseRecord(int handler)
{
	_RecordTimePoints.erase(handler);
	_RecordTimeIntervals.erase(handler);
}

clock_t TimeRecordUtil::GetAverage(int handler)
{
	clock_t result = 0;
	const auto& ever_records = GetEverRecords(handler);
	if(ever_records.empty())
		return result;
	for(auto& each : ever_records)
		result += each;
	return result / ever_records.size();
}

const std::vector<clock_t>& TimeRecordUtil::GetEverRecords(int handler)
{
	return _RecordTimeIntervals[handler];
}

